package cn.bdqn.filter;

import cn.bdqn.dao.UserDao;
import cn.bdqn.entity.AuthorityUser;
import cn.bdqn.entity.Payload;
import cn.bdqn.util.JwtUtil;
import cn.bdqn.util.RsaKeyProperties;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @ProjectName: springbootSecurityJwtOAuth
 * @Package: cn.bdqn.filter
 * @Author: huat
 * @Date: 2019/12/26 13:18
 * @Version: 1.0
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private UserDao userDao;
    @Autowired
    private RsaKeyProperties rsaKeyProperties;
    //这个方法是在访问接口之前执行的，我们只需要在这里写验证登陆状态的业务逻辑，就可以在用户调用指定接口之前验证登陆状态了
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求头中的信息
        String header=request.getHeader("Authorization");
        if (null!=header&&header.startsWith("bearer ")){
            //获取token
            String requestToken=header.replace("bearer ","");
            //验证token是否正确
            Payload<AuthorityUser> payload= JwtUtil.getInfoFromToken(requestToken,rsaKeyProperties.getPublicKey(), AuthorityUser.class);
            AuthorityUser user=payload.getUserInfo();
            String token=userDao.getTokenById(user.getId());
            if(null!=token&&!"".equals(token)){
                if( token.equals(requestToken)){
                    return true;
                }
                //如果没有登陆提示用户进行登陆
                response.setContentType("application/json;charset=utf-8");
                //返回403状态码
                response.setStatus(HttpServletResponse.SC_FORBIDDEN);
                //响应流
                PrintWriter out = response.getWriter();
                //封装返回数据
                Map<String, Object> resultMap = new HashMap<String, Object>();
                resultMap.put("code", HttpServletResponse.SC_FORBIDDEN);
                resultMap.put("data", "您的账号在其他地方已登录");
                resultMap.put("msg", "请登录");
                //new ObjectMapper().writeValueAsString(resultMap)将map转成json
                out.write(new ObjectMapper().writeValueAsString(resultMap));
                out.flush();
                out.close();
                return false;
            }
        }
        //如果没有登陆提示用户进行登陆
        response.setContentType("application/json;charset=utf-8");
        //返回403状态码
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        //响应流
        PrintWriter out = response.getWriter();
        //封装返回数据
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("code", HttpServletResponse.SC_FORBIDDEN);
        resultMap.put("data", "");
        resultMap.put("msg", "请登录");
        //new ObjectMapper().writeValueAsString(resultMap)将map转成json
        out.write(new ObjectMapper().writeValueAsString(resultMap));
        out.flush();
        out.close();

        return false;
    }



}

